# _*_ coding:utf-8 _*_
# @Time  : 2022-03-13
# @Author: zizle

import random
import time
import json
import datetime
import pathlib
import requests
from loguru import logger
logger.add('error.log')

# 获取列表

LOGIN_COOKIE = "ASP.NET_SessionId=jrmfo121jsnmcfghb00xzfue; FuturesDaily_Mac=2E28C9424E003194DB382B68C66CF0F6; FuturesDaily_Licence=3DBFA84844D0A476D9417D980C66ADA4; FuturesDaily_2018/*=7E00C1AEB6152D864DEA6E66A29BE9DB2701FE629066F9A5335018BF0A0098536F80CEDE8FC17647A2FDFD4599C1F86B1B20CBC5BC4C36BE8794CAD1A4BA60031D3F11C6909E290086DB99895BB432BC7D957524C59C72ACADF2472AC1857B2FDCB6F27476E13A099799D0870E5F051DE6A4BDAE08383A3669DD1F9958000F9309F7993D9D80F88E457F00A062C65D65D6BB560B5B9A0A1D2FBF36F47E0A8CD165D698268B9065816F39F69194B36FEB897DC04C459ED7C13B732C741B01DD8CDDC8DEE814C9709BB8D233D7BDF9D2462F15FF5FB83F7BB73EADC9F6BAE8DB0F84197F097B676AC2"
USE_COOKIE = True
USE_PROXIES = {'https': '221.4.241.198:9091'} if USE_COOKIE else False


def get_pdf(day, qsrange, qishu):
    datetime_obj = datetime.datetime.strptime(day, '%Y-%m-%d')
    folder = 'DailyPdf/%04d/%s' % (datetime_obj.year, datetime_obj.strftime('%Y-%m-%d'))
    save_folder = pathlib.Path(folder)
    if not save_folder.exists():
        save_folder.mkdir(parents=True)

    suffixs = ['01', '02', '03', '04', '05', '06', '07', '08']
    remote_url = 'http://paper.7h365.com/Content/Dir_DailyPdf' + f'/{qsrange}/{qishu}-'

    for sf in suffixs:
        time.sleep(1)
        save_path = save_folder.joinpath(f'{day}-{qishu}-{sf}.pdf')
        pdf_url = remote_url + f'{sf}.pdf'
        c = request_pdf(pdf_url, save_path)
        if not c:
            break

    # 验证文件夹内有几个文件
    pdf_count = list(save_folder.glob('*.pdf'))
    if len(pdf_count) % 2 == 1:
        logger.error(f'{day} PDF数量：{len(pdf_count)}个。')


def request_pdf(remote_url, save_path):
    headers = {
        'Host': 'paper.7h365.com',
        'Connection': 'keep-alive',
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest',
        'Referer': 'http://paper.7h365.com/Members/MemberIndex',
        'Accept-Encoding': 'gzip,deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
    }
    if USE_COOKIE:
        headers["Cookie"] = LOGIN_COOKIE
    try:
        if USE_PROXIES:
            r = requests.get(url=remote_url, headers=headers, proxies=USE_PROXIES)
        else:
            r = requests.get(url=remote_url, headers=headers)
        if len(r.content) <= 3367:
            raise ValueError('PASS')
        with open(save_path, 'wb') as fp:
            fp.write(r.content)
    except Exception as e:
        print(f'获取{save_path}失败：{e}')
        return False
    else:
        print(f'保存{save_path}成功！')
        return True


if __name__ == '__main__':
    get_pdf('2009-01-07', '3301-3400', '3334')
